package com.setup.trac.listeners;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.setup.trac.dao.DAOService;
import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.condition.FindAllegatiBySessionIdAndTemporaneo;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.SQLCondition;

public class TracSetupSessionListener implements HttpSessionListener {

	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub

	}

	public void sessionDestroyed(HttpSessionEvent sessionEvent) {
		HttpSession session = sessionEvent.getSession();

		ApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(session.getServletContext());

		SearchService searchService = (SearchService) ctx
				.getBean("searchService");
		DAOService daoService = (DAOService) ctx.getBean("daoService");

		SQLCondition sqlCondition = new FindAllegatiBySessionIdAndTemporaneo(
				session.getId(), true);
		Allegati[] allegati = searchService.find(new Allegati[0], sqlCondition,
				Allegati.class);
		for (int i = 0; i < allegati.length; i++) {
			Allegati allegato = allegati[i];
			daoService.delete(allegato);
		}
	}

}
